#include "stdafx.h"
#include "libraries.h"

#include "Application.h"
#include "Filesystem.h"
#include "Mesh.h"

using namespace Cvekas;

class MeshTest: public Application
{
public:
	MeshTest(HINSTANCE instance, const std::string& name, const std::string& log_filename)
		: Application(instance, name, log_filename), 
		  camera(Vector3(0.0f, 0.0f, -4.0f), Vector3(0.0f, 0.0f, 1.0f), Vector3(0.0f, 1.0f, 0.0f)) 
	{
		Filesystem::init();
	}

	virtual ~MeshTest()
	{
	}

	virtual void initVideoDevice()
	{
		settings->insert("video", VideoSettings());

		(*settings)["video"]["ScreenWidth"] = 800;
		(*settings)["video"]["ScreenHeight"] = 600;
		(*settings)["video"]["VSync"] = false;
		(*settings)["video"]["Fullscreen"] = false;

		window = WindowPtr(new Window(instance, name));
		video_device->init(window);
		video_device->setProjectionMatrix(Matrix::perspective(pi / 4.0f, 800.0f / 600.0f, 1.0f, 80.0f));
	}

	virtual void init()
	{
		MeshPtr monkey_mesh = MeshPtr(new Mesh(Filesystem::redirect("Monkey.cmf")));
		EffectPtr monkey_effect = effect_manager->load("Monkey", Filesystem::redirect("Monkey.fx"));
		monkey = RenderableMeshPtr(new RenderableMesh(monkey_mesh, monkey_effect, EffectParamsPtr(), 0));
	}

	virtual bool update()
	{
		float t = Timer::getTimeMs() / 1000.0f;
		monkey->setRotation(Vector3(0.0f, t, 0.0f));
		return true;
	}

	virtual bool render()
	{
		video_device->getRenderingParams().setCamera(camera);

		video_device->beginScene();
		main_renderer->prepare(*monkey);
		main_renderer->render();
		video_device->endScene();
		main_renderer->endFrame();

		return true;
	}
private:
	SimpleCamera camera;
	RenderableMeshPtr monkey;
};

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)
{
	try
	{
		MeshTest app(hInstance, "Mesh", "mesh.log");
		app.run();
	}
	catch (std::exception& e)
	{
		MessageBox(NULL, e.what(), "Fatal error", NULL);
	}
	return 0;
}
